package net.jescort.web.servlet.controller.message;

import net.jescort.domain.forum.Message;
import net.jescort.domain.user.User;
import net.jescort.repository.EscortRepository;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 11-7-16
 * Time: 下午7:02
 */
@Controller
@SessionAttributes(types = Message.class)
public class MessageShow
{
    @Resource(name = "escortRepository")
    private EscortRepository escortRepository;


    @RequestMapping(value = {"/message/{id}"}, method = RequestMethod.GET)
    public ModelAndView messageHandler(@PathVariable("id") Integer id)
    {
        ModelAndView mav = new ModelAndView("messages/show");
        User currentUser = (User)SecurityUtils.getSubject().getPrincipal();
        Message message = escortRepository.getMessage(id);

        List<User> recipients = message.getRecipients();
        boolean isRecipient = false;
        for(User recipient : recipients)
        {
            if(recipient.equals(currentUser))
            {
                isRecipient = true;
                break;
            }
        }
        if(!isRecipient)
        {
            throw new RuntimeException();
        }
        mav.addObject("message", message);
        return mav;
    }
}
